import {defineStore} from 'pinia'
import {ref} from 'vue'
import {publicKeysValidate, publicGetRota} from "@/apis/PublicApi";
import {ElMessage} from "element-plus";


export const usePublicStore = defineStore('public', () => {
        // const keys = ref(["BIha1bJk70Kua"])
        const keys = ref([])
        const key = ref('')
        // 添加key
        const setKeys = (key) => {
            if (!keys.value.includes(key)) {
                keys.value.push(key)
            }
        }

        // 更新key
        const updateKey = (newKey) => {
            key.value = newKey
        }

        // 验证密钥的合法性
        const keyValidate = () => {
            const validateInfo = ref()
            if (keys.value.length !== 0) {
                publicKeysValidate(keys).then(res => {
                    validateInfo.value = res.data
                    for (let i = 0; i < validateInfo.value.length; i++) {
                        // 如果valid为false
                        if (!validateInfo.value[i].valid) {
                            // 从keys中移除对应的密钥
                            let index = keys.value.indexOf(validateInfo.value[i].key);
                            if (index !== -1) {
                                keys.value.splice(index, 1);
                            }
                        }
                    }
                });
            }
        }

        // 获取值班表
        const getRota = (queryKey, callBack) => {
            publicGetRota(queryKey).then(res => {
                if (res.msg === "暂时还没有生成值班表，请前往生成值班表，或者等值班表生成之后再来获取") {
                    ElMessage(
                        {
                            type: "warning",
                            message: res.msg,
                            showClose: true,
                            duration: 0
                        }
                    )
                } else {
                    key.value = queryKey
                    ElMessage.success("获取成功")
                }
                callBack(res.data.rota)
            })
        }


        return {
            keys,
            key,
            setKeys,
            updateKey,
            getRota,
            keyValidate
        }
    },
    {
        persist: {
            storage: localStorage,
            paths: ['keys', 'key'],
        }
    }
)